import { Scene } from '@babylonjs/core/scene';
import { AbstractGroup, IAbstractGroupOptions } from './abstract-group';
import { IUIRadioOptions, UIRadio } from './ui-radio';
import { IHandle } from '../../data/data-handle';


/**
 * 单选按钮组控件参数对象
 * @param checkedValue 选中项
 * @param revocable 是否可撤销
 */
interface IUIRadioGroupOptions extends IAbstractGroupOptions<IUIRadioOptions> {
    checkedValue?: string | null | undefined,
    revocable?: boolean,
}


/**
 * 单选按钮组控件
 * @param name 名称
 * @param scene 所在场景
 * @param options 参数对象
 */
class UIRadioGroup extends AbstractGroup {

    private _checkedValue: string | undefined;
    private _revocable!: boolean;

    constructor(name: string, scene: Scene, options?: IUIRadioGroupOptions) {
        super(name, scene, options);
        const ops = options || {};
        this.checkedValue = ops.checkedValue;
    }

    /**
     * 设置选中项
     */
    public set checkedValue(checkedValue: string | undefined | null) {
        if (!checkedValue) {
            if (!this._revocable) return;
        }
        for (const item of this.items) {
            (item as UIRadio).isChecked = checkedValue === item.key;
        }
    }

    /**
     * 获取选中项
     */
    public get checkedValue(): string | undefined {
        return this._checkedValue;
    }

    public onChange(func: (value: string | undefined) => void): IHandle<string | undefined> {
        return super.onChange(func);
    }

    protected generateItem(name: string, scene: Scene, itemOptions: IUIRadioOptions, groupOptions: IUIRadioGroupOptions): UIRadio {

        this._revocable = !!groupOptions.revocable;
        itemOptions.revocable = this._revocable;
        const radio = new UIRadio(name, scene, itemOptions);

        radio.onChange((isChecked: boolean) => {
            if (isChecked) {
                this._checkedValue = radio.key;
                for (const item of this.items) {
                    if (item.key === this._checkedValue) continue;
                    (item as UIRadio).isChecked = false;
                }
            } else {
                if (!this._revocable) return;
                if (this._checkedValue !== radio.key) return;
                this._checkedValue = undefined;
            }
            if (!this.avoidEventHandle) this.changeHandles.forEach(handle => handle.callback(this._checkedValue));
        });
        return radio;
    }

}


/**
 * 创建单选按钮组控件
 * @param name 名称
 * @param scene 所在场景
 * @param options 参数对象
 * @param changeCallback 值改变时的回调函数
 * @returns 单选按钮组控件
 */
const CreateUIRadioGroup = (name: string, scene: Scene, options?: IUIRadioGroupOptions, changeCallback?: { (value: string | undefined): void }): UIRadioGroup => {
    const group = new UIRadioGroup(name, scene, options);
    if (changeCallback) group.onChange(changeCallback);
    return group;
};


export { UIRadioGroup, CreateUIRadioGroup };
export type { IUIRadioGroupOptions };